let express = require("express")();
let expressStatic = require("express-static");
let mysql = require("mysql");
let bodyParser = require('body-parser');//解析,用req.body获取post参数
	
const port = 80;

// 为body-parser进行配置（server代表express执行函数后返回的对象）
express.use(bodyParser.json());
express.use(bodyParser.urlencoded({extended: false}));

//规划一个数据库连接
let sql = mysql.createConnection({
    host     : 'localhost',
    user     : 'root', 
    password : 'root',
    database : '2006',
    timezone:"08:00"
})

//尝试连接
sql.connect();

//查看数据库(初始渲染)
express.get("/alllist",(resquest,response)=>{
    sql.query(`SELECT * FROM student`,(error,data)=>{
        if(error){
            response.send(error);
            console.log(error);
        }else{
            // console.log(data);
            response.send(JSON.stringify(data));
        }
    })
})

//删除学员
express.get("/removeid",(request,response)=>{
    // console.log(request.query.id);
    let aaa = request.query.id;
    sql.query(`delete  from student where id=${aaa}`,(error,data)=>{
        if(error){
            response.send("error");
        }else{
            response.send("success");
        }
    })
})

//添加学员
express.get("/addstu",(request,response)=>{
    // console.log(request.query);
    let aa = request.query;
    sql.query(`insert into student (name,age,sex,city,time) values ("${aa.name}","${aa.age}","${aa.sex}","${aa.city}","${aa.time}")`,(error,data)=>{
        if(error){
            response.send("添加失败");
        }else{
            response.send("添加成功");
        }
    })
})


//注册（数据库添加数据）
express.get("/adduser",(request,response)=>{
    console.log(request.query);
    let q = request.query;
    sql.query(`INSERT INTO user (username,password,usertype,name) VALUES ("${q.username}","${q.password}",${q.usertype},"${q.name}")`,(error,data)=>{
        if(error){
            response.send("error");
            console.log(error);
        }else{
            response.send("success");
            console.log(`${request.query.username}用户新增成功`);
        }
    });
})





//登录
express.get("/login",(request,response)=>{
    let q = request.query;
    console.log(q)
    sql.query(`SELECT * FROM user WHERE username="${q.username}" AND password="${q.password}"`,(error,data)=>{
        if(error){
            response.send("error");
            console.log(error);
        }else{
            console.log(data);
            if(data.length === 0){
                response.send("error");
            }else{
                response.send('success');
            }
        }
    })
})



//如果接收到来自前端的请求的话，我该去哪里去给他找文件
express.use(expressStatic(__dirname + '/static'));
console.log(`running at ${port}`);
express.listen(port);